package com.gpb.common.directive;
import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gpb.common.method.JSON2MapMethod;
import com.gpb.common.utils.DirectiveUtils;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;


/**
 * 工具集
 * @author Poppy Kwoks
 * @dateTime May 11, 2014  9:29:04 AM
 */
public class ToolsDirective implements TemplateDirectiveModel {
	private static final Logger log = LoggerFactory
			.getLogger(ToolsDirective.class);
	
	/**
	 * 工具方法集
	 */
	private Map toolsVariables;
	
	@SuppressWarnings("unchecked")
	public void execute(Environment env, Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
		//添加到 paramWrap 
		Iterator<String> iterator=toolsVariables.keySet().iterator();
		String key=null;
		while (iterator.hasNext()) {
			key=iterator.next();
			paramWrap.put(key,  DEFAULT_WRAPPER.wrap(toolsVariables.get(key)));
			//paramWrap.put(key, DEFAULT_WRAPPER.wrap(toolsVariables.get(key)));
			//paramWrap.put(key, (TemplateModel)toolsVariables.get(key));
		}
		paramWrap.put("jsona", new JSON2MapMethod());
		//DirectiveUtils.addParamsToVariable(env, paramWrap);
		//paramWrap.put("goods", DEFAULT_WRAPPER.wrap(obj));
		Map<String, TemplateModel> origMap = DirectiveUtils.addParamsToVariable(env, paramWrap);
		if(body!=null){
			body.render(env.getOut());
			DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap);
		}

	}
	public Map getToolsVariables() {
		return toolsVariables;
	}
	public void setToolsVariables(Map toolsVariables) {
		this.toolsVariables = toolsVariables;
	}
	
	
}
